package com.share.quartz.service;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import org.apache.log4j.Logger;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.quartz.SchedulerContext;
import org.quartz.SchedulerException;
import org.springframework.context.ApplicationContext;

/**
 * quartz 基础job类   调用Spring配置好的  bean  和    定义的调用的方法
 * @author xianwei
 *
 */
public class QuartzJobBean implements Job {
	private Logger logger = Logger.getLogger(getClass());
	@Override
	public void execute(JobExecutionContext context)
			throws JobExecutionException {
		try {
			//获取application context key
			String applicationContextKey = "applicationContext" ;
			SchedulerContext schedulerContext = context.getScheduler().getContext();
			if(applicationContextKey!=null&&!"".equals(applicationContextKey)){
				//根据配置的  key 直接获取  applicationContext 
				ApplicationContext applicationContext = (ApplicationContext) schedulerContext.get(applicationContextKey);
				logger.debug("quartz任务基础调度类");
				String targetBeanId = (String)context.getMergedJobDataMap().get("targetObjectId");
				String targetObjectMethos = (String)context.getMergedJobDataMap().get("targetObjectMethos");
				if(targetBeanId==null||"".equals(targetBeanId))
					return;
				Object targetBean = applicationContext.getBean(targetBeanId);
				if(null == targetBean)
					return;
				try {
					Class<?> clazz = targetBean.getClass();
					//获取 方法并执行
					Method exeMethod = clazz.getMethod(targetObjectMethos);
					exeMethod.invoke(targetBean);
				} catch (SecurityException e) {
					e.printStackTrace();
				} catch (NoSuchMethodException e) {
					logger.info("-----找不到配置为方法------------"+targetObjectMethos);
					e.printStackTrace();
				}catch (IllegalArgumentException e) {
					logger.info("-----方法参数类型错误------------");
					e.printStackTrace();
				} catch (IllegalAccessException e) {
					e.printStackTrace();
				} catch (InvocationTargetException e) {
					e.printStackTrace();
				}
				/*	version  1.0  需实现接口 Quartzjob  
				 * // 判断是否是实现了MyJob接口
				if(!(targetBean instanceof QuartzJob))
					return;
				
				// 执行相应的任务
				((QuartzJob)targetBean).execute();*/
			}else{
				logger.info("未找到Spring上下文环境--");
			}
		} catch (SchedulerException e1) {
			e1.printStackTrace();
		}
		
	}

}
